﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SpridTest
{
    /// <summary>
    /// HTTP请求工具类
    /// </summary>
    public class HttpRequestUtil
    {
        /// <summary>
        /// 获取页面
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetPageHtml(string url)
        {
            //设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)";
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送post请求
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            //返回结果网页的html代码
            string content = sr.ReadToEnd();
            return content;
        }

        public static void HttpDownLoadFile(string url)
        {
            int pos = url.LastIndexOf("/");
            int end = url.IndexOf("?");
            string fileName = url.Substring(pos,end- pos);

            string path = Application.StartupPath + "\\download";
            //判断路径是否存在
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string filePathName = path + "\\" + fileName;
            //判断文件是否存在
            if (File.Exists(filePathName))
            { 
                return;
            }

            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)";

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;

            Stream responseStream = response.GetResponseStream();
            //创建本地文件流
            Stream stream = new FileStream(filePathName, FileMode.Create);
            byte[] bArr = new byte[1024];

            int size = responseStream.Read(bArr, 0, bArr.Length);
            while (size > 0)
            {
                stream.Write(bArr, 0, size);
                size = responseStream.Read(bArr, 0, bArr.Length);
            }
            stream.Close();
            responseStream.Close();
        }
    }
}
